#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LangGraph多智能体HR系统
完全基于LangGraph模块构建的多智能体架构
不使用任何try语句，纯LangGraph实现
"""

import os
import json
import logging
from datetime import datetime
from typing import Dict, List, Any, Literal, TypedDict, Annotated
from typing_extensions import NotRequired

# LangGraph核心模块
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages

# LangChain核心模块
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

# 数据管理
from data_manager import data_manager
from agent_prompts import agent_prompts
from candidate_deep_analysis import candidate_analysis_tools

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# ==================== 1. 系统状态定义 ====================

class MultiAgentState(TypedDict):
    """多智能体系统全局状态"""
    # 基础会话信息
    session_id: str
    user_id: str
    timestamp: str
    
    # 用户交互
    original_query: str
    messages: Annotated[List[Any], add_messages]
    
    # 任务管理
    task_plan: NotRequired[List[Dict[str, Any]]]
    current_task: NotRequired[Dict[str, Any]]
    task_results: NotRequired[Dict[str, Any]]
    
    # 业务数据
    candidates: NotRequired[List[Dict[str, Any]]]
    analysis_results: NotRequired[Dict[str, Any]]
    ui_commands: NotRequired[List[Dict[str, Any]]]
    
    # 系统状态
    next_agent: NotRequired[str]
    final_response: NotRequired[str]
    status: str

# ==================== 2. 工具定义 ====================

@tool
def search_candidates_by_criteria(criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
    """根据条件搜索候选人"""
    logger.info(f"🔍 搜索候选人: {criteria}")
    
    skills = criteria.get('skills', [])
    min_experience = criteria.get('min_experience', 0)
    location = criteria.get('location', '')
    
    matching_candidates = []
    
    for resume in data_manager.resumes:
        # 技能匹配
        skill_match = False
        if not skills:
            skill_match = True
        else:
            resume_skills_str = ' '.join(resume.skills) if isinstance(resume.skills, list) else str(resume.skills)
            for skill in skills:
                if skill.lower() in resume_skills_str.lower():
                    skill_match = True
                    break
        
        # 经验匹配
        experience_years = resume.experience_years or 0
        experience_match = experience_years >= min_experience
        
        # 地点匹配  
        location_match = True
        if location:
            location_match = location.lower() in resume.location.lower()
        
        if skill_match and experience_match and location_match:
            matching_candidates.append({
                'id': resume.id,
                'name': resume.name,
                'skills': resume.skills if isinstance(resume.skills, list) else [str(resume.skills)],
                'experience': experience_years,
                'location': resume.location,
                'education': getattr(resume, 'education', getattr(resume, 'qualification', '未知'))
            })
    
    logger.info(f"✅ 找到 {len(matching_candidates)} 个匹配候选人")
    return matching_candidates

@tool
def analyze_candidate_compatibility(candidate_id: str, job_requirements: Dict[str, Any]) -> Dict[str, Any]:
    """分析候选人与岗位的匹配度"""
    logger.info(f"🔍 分析候选人 {candidate_id} 匹配度")
    
    candidate = None
    for resume in data_manager.resumes:
        if resume.id == candidate_id:
            candidate = resume
            break
    
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    # 计算匹配分数
    score = 0
    details = {}
    
    # 技能匹配 (40分)
    required_skills = job_requirements.get('skills', [])
    skill_score = 0
    if required_skills:
        matched_skills = 0
        candidate_skills_str = ' '.join(candidate.skills) if isinstance(candidate.skills, list) else str(candidate.skills)
        for skill in required_skills:
            if skill.lower() in candidate_skills_str.lower():
                matched_skills += 1
        skill_score = (matched_skills / len(required_skills)) * 40
    else:
        skill_score = 40
    
    # 经验匹配 (30分)
    required_exp = job_requirements.get('min_experience', 0)
    candidate_exp = candidate.experience_years or 0
    if candidate_exp >= required_exp:
        exp_score = 30
    else:
        exp_score = (candidate_exp / required_exp) * 30 if required_exp > 0 else 30
    
    # 教育背景 (20分)
    education = getattr(candidate, 'education', getattr(candidate, 'qualification', '未知'))
    edu_score = 15 if '本科' in education or '学士' in education else 10
    
    # 地点匹配 (10分)
    required_location = job_requirements.get('location', '')
    loc_score = 10 if not required_location or required_location.lower() in candidate.location.lower() else 5
    
    total_score = skill_score + exp_score + edu_score + loc_score
    
    return {
        'candidate_id': candidate_id,
        'total_score': round(total_score, 1),
        'skill_score': round(skill_score, 1),
        'experience_score': round(exp_score, 1),
        'education_score': round(edu_score, 1),
        'location_score': round(loc_score, 1),
        'details': {
            'name': candidate.name,
            'skills': candidate.skills if isinstance(candidate.skills, list) else [str(candidate.skills)],
            'experience': f"{candidate_exp}年",
            'education': getattr(candidate, 'education', getattr(candidate, 'qualification', '未知')),
            'location': candidate.location
        }
    }

@tool
def update_candidate_record(candidate_id: str, updates: Dict[str, Any]) -> Dict[str, Any]:
    """更新候选人记录"""
    logger.info(f"📝 更新候选人 {candidate_id} 记录: {updates}")
    
    # 在实际系统中，这里会连接数据库
    # 现在我们模拟更新操作
    operation_log = {
        'candidate_id': candidate_id,
        'timestamp': datetime.now().isoformat(),
        'updates': updates,
        'status': 'success'
    }
    
    logger.info(f"✅ 候选人记录更新成功: {operation_log}")
    return operation_log

@tool
def generate_ui_command(action: str, payload: Dict[str, Any]) -> Dict[str, Any]:
    """生成UI更新指令"""
    logger.info(f"🎨 生成UI指令: {action} - {payload}")
    
    ui_command = {
        'action': action,
        'payload': payload,
        'timestamp': datetime.now().isoformat()
    }
    
    return ui_command

# 工具列表
hr_tools = [
    search_candidates_by_criteria,
    analyze_candidate_compatibility, 
    update_candidate_record,
    generate_ui_command
] + candidate_analysis_tools

# ==================== 3. 大模型配置 ====================

def create_multi_agent_model():
    """创建多智能体模型"""
    # 检查API密钥
    dashscope_key = os.getenv("DASHSCOPE_API_KEY")
    openai_key = os.getenv("OPENAI_API_KEY")
    
    if dashscope_key:
        logger.info("🚀 使用阿里云通义千问模型")
        # 临时清除代理设置以避免连接问题
        original_proxies = {}
        proxy_vars = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']
        for var in proxy_vars:
            if var in os.environ:
                original_proxies[var] = os.environ[var]
                del os.environ[var]
        
        model = ChatOpenAI(
            model="qwen-plus",
            openai_api_key=dashscope_key,
            openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
            temperature=0.1
        )
        
        # 恢复代理设置
        for var, value in original_proxies.items():
            os.environ[var] = value
    elif openai_key:
        logger.info("🚀 使用OpenAI GPT-4模型")
        # 临时清除代理设置以避免连接问题
        original_proxies = {}
        proxy_vars = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']
        for var in proxy_vars:
            if var in os.environ:
                original_proxies[var] = os.environ[var]
                del os.environ[var]
        
        model = ChatOpenAI(
            model="gpt-4-turbo-preview",
            temperature=0.1
        )
        
        # 恢复代理设置
        for var, value in original_proxies.items():
            os.environ[var] = value
    else:
        logger.warning("⚠️ 未找到API密钥，使用演示模型")
        # 创建演示模型
        raise Exception("未找到API密钥")
    
    return model.bind_tools(hr_tools)

# 全局模型实例
multi_agent_model = create_multi_agent_model()

# ==================== 4. 智能体节点定义 ====================

def interaction_module(state: MultiAgentState) -> Dict[str, Any]:
    """交互模块 - 处理用户输入，启动系统"""
    logger.info("🎯 Interaction Module: 处理用户输入")
    
    user_query = state["original_query"]
    session_id = state.get("session_id", f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
    
    # 标准化请求格式
    standardized_request = {
        "session_id": session_id,
        "user_id": state.get("user_id", "hr_user_001"),
        "timestamp": datetime.now().isoformat(),
        "query": user_query
    }
    
    logger.info(f"📤 标准化请求: {standardized_request}")
    
    return {
        "session_id": session_id,
        "messages": [HumanMessage(content=user_query)],
        "next_agent": "orchestrator",
        "status": "processing"
    }

def orchestrator_agent(state: MultiAgentState) -> Dict[str, Any]:
    """Orchestrator Agent - 总调度中心"""
    logger.info("🧠 Orchestrator Agent: 分析任务并制定计划")
    
    # 获取可配置的系统提示词
    orchestrator_prompt = agent_prompts.get_prompt("orchestrator")

    messages = [SystemMessage(content=orchestrator_prompt)] + state["messages"]
    
    response = multi_agent_model.invoke(messages)
    
    # 分析响应，决定下一步
    if hasattr(response, 'tool_calls') and response.tool_calls:
        # 需要调用工具
        logger.info(f"🔧 Orchestrator决定调用工具: {[tc['name'] for tc in response.tool_calls]}")
        return {
            "messages": [response],
            "next_agent": "tool_executor",
            "current_task": {"agent": "orchestrator", "action": "tool_execution"}
        }
    else:
        # 分析用户意图，决定下一个智能体
        content = response.content.lower()
        if "深度分析" in content or "详细分析" in content or "可视化" in content or "雷达图" in content or "柱状图" in content:
            next_agent = "candidate_deep_analysis"
        elif "筛选" in content or "搜索" in content or "分析" in content:
            next_agent = "candidate_analysis"
        elif "更新" in content or "修改" in content or "添加" in content:
            next_agent = "record_keeping" 
        elif "界面" in content or "显示" in content or "排序" in content:
            next_agent = "workbench_ui"
        else:
            next_agent = "candidate_analysis"  # 默认
        
        logger.info(f"🎯 Orchestrator决定转交给: {next_agent}")
        
        return {
            "messages": [response],
            "next_agent": next_agent,
            "current_task": {"target_agent": next_agent, "context": response.content}
        }

def candidate_analysis_agent(state: MultiAgentState) -> Dict[str, Any]:
    """CandidateAnalysis Agent - 候选人分析师"""
    logger.info("👨‍💼 CandidateAnalysis Agent: 执行候选人分析")
    
    # 获取可配置的分析师提示词
    analysis_prompt = agent_prompts.get_prompt("candidate_analysis")

    # 只使用完整的消息，避免工具调用消息不完整的问题
    clean_messages = [SystemMessage(content=analysis_prompt)]
    
    # 添加最后一个完整的AI消息（不包含工具调用）
    for msg in reversed(state["messages"]):
        if isinstance(msg, AIMessage) and not (hasattr(msg, 'tool_calls') and msg.tool_calls):
            clean_messages.append(msg)
            break
    
    response = multi_agent_model.invoke(clean_messages)
    
    if hasattr(response, 'tool_calls') and response.tool_calls:
        logger.info(f"🔧 CandidateAnalysis调用工具: {[tc['name'] for tc in response.tool_calls]}")
        return {
            "messages": [response],
            "next_agent": "tool_executor",
            "current_task": {"agent": "candidate_analysis", "action": "analysis"}
        }
    else:
        # 检查是否需要深度分析
        if "深度分析" in response.content or "详细分析" in response.content or "可视化" in response.content:
            next_agent = "candidate_deep_analysis"
        elif "界面更新" in response.content or "显示" in response.content:
            next_agent = "workbench_ui"
        elif "记录" in response.content or "保存" in response.content:
            next_agent = "record_keeping"
        else:
            next_agent = "completion"
        
        return {
            "messages": [response],
            "next_agent": next_agent,
            "analysis_results": {"completed": True, "agent": "candidate_analysis"}
        }

def candidate_deep_analysis_agent(state: MultiAgentState) -> Dict[str, Any]:
    """CandidateDeepAnalysis Agent - 候选人深度分析师"""
    logger.info("🔬 CandidateDeepAnalysis Agent: 执行候选人深度分析")
    
    # 深度分析提示词
    deep_analysis_prompt = """你是专业的候选人深度分析师，专门负责：
1. 生成候选人多维度能力雷达图
2. 创建技能匹配度对比柱状图
3. 提供全面的分析报告和可视化数据
4. 给出详细的面试建议和风险评估

当用户需要候选人详情分析时，请使用深度分析工具生成：
- 能力雷达图 (技术能力、项目经验、沟通能力等8个维度)
- 技能匹配度柱状图 (与岗位要求的对比)
- 综合分析报告 (包含评分、建议、风险点、面试问题)

请根据用户需求调用相应的分析工具。"""

    # 只使用完整的消息，避免工具调用消息不完整的问题
    clean_messages = [SystemMessage(content=deep_analysis_prompt)]
    
    # 添加最后一个完整的AI消息（不包含工具调用）
    for msg in reversed(state["messages"]):
        if isinstance(msg, AIMessage) and not (hasattr(msg, 'tool_calls') and msg.tool_calls):
            clean_messages.append(msg)
            break
    
    response = multi_agent_model.invoke(clean_messages)
    
    if hasattr(response, 'tool_calls') and response.tool_calls:
        logger.info(f"🔧 CandidateDeepAnalysis调用工具: {[tc['name'] for tc in response.tool_calls]}")
        return {
            "messages": [response],
            "next_agent": "tool_executor",
            "current_task": {"agent": "candidate_deep_analysis", "action": "deep_analysis"}
        }
    else:
        # 深度分析完成，通常需要更新界面显示结果
        return {
            "messages": [response],
            "next_agent": "workbench_ui",
            "analysis_results": {"completed": True, "agent": "candidate_deep_analysis", "type": "deep_analysis"}
        }

def record_keeping_agent(state: MultiAgentState) -> Dict[str, Any]:
    """RecordKeeping Agent - 记录与状态管理员"""
    logger.info("📚 RecordKeeping Agent: 管理数据记录")
    
    # 获取可配置的记录管理提示词
    record_prompt = agent_prompts.get_prompt("record_keeping")

    # 只使用完整的消息，避免工具调用消息不完整的问题
    clean_messages = [SystemMessage(content=record_prompt)]
    
    # 添加最后一个完整的AI消息（不包含工具调用）
    for msg in reversed(state["messages"]):
        if isinstance(msg, AIMessage) and not (hasattr(msg, 'tool_calls') and msg.tool_calls):
            clean_messages.append(msg)
            break
    
    response = multi_agent_model.invoke(clean_messages)
    
    if hasattr(response, 'tool_calls') and response.tool_calls:
        logger.info(f"🔧 RecordKeeping调用工具: {[tc['name'] for tc in response.tool_calls]}")
        return {
            "messages": [response],
            "next_agent": "tool_executor",
            "current_task": {"agent": "record_keeping", "action": "data_update"}
        }
    else:
        return {
            "messages": [response],
            "next_agent": "workbench_ui",  # 通常更新数据后需要更新界面
            "task_results": {"record_keeping": "completed"}
        }

def workbench_ui_agent(state: MultiAgentState) -> Dict[str, Any]:
    """WorkbenchUI Agent - 工作台交互管家"""
    logger.info("🎨 WorkbenchUI Agent: 处理界面更新")
    
    # 获取可配置的界面管家提示词
    ui_prompt = agent_prompts.get_prompt("workbench_ui")

    # 只使用完整的消息，避免工具调用消息不完整的问题
    clean_messages = [SystemMessage(content=ui_prompt)]
    
    # 添加最后一个完整的AI消息（不包含工具调用）
    for msg in reversed(state["messages"]):
        if isinstance(msg, AIMessage) and not (hasattr(msg, 'tool_calls') and msg.tool_calls):
            clean_messages.append(msg)
            break
    
    response = multi_agent_model.invoke(clean_messages)
    
    if hasattr(response, 'tool_calls') and response.tool_calls:
        logger.info(f"🔧 WorkbenchUI调用工具: {[tc['name'] for tc in response.tool_calls]}")
        return {
            "messages": [response],
            "next_agent": "tool_executor",
            "current_task": {"agent": "workbench_ui", "action": "ui_update"}
        }
    else:
        return {
            "messages": [response],
            "next_agent": "completion",
            "ui_commands": [{"action": "interface_updated", "status": "success"}]
        }

def tool_executor(state: MultiAgentState) -> Dict[str, Any]:
    """工具执行器"""
    logger.info("🛠️ Tool Executor: 执行工具调用")
    
    last_message = state["messages"][-1]
    current_task = state.get("current_task", {})
    
    if not hasattr(last_message, 'tool_calls') or not last_message.tool_calls:
        logger.error("❌ 没有找到工具调用请求")
        return {
            "messages": [AIMessage(content="工具执行失败：没有找到工具调用请求")],
            "next_agent": "completion"
        }
    
    tool_results = []
    for tool_call in last_message.tool_calls:
        tool_name = tool_call["name"]
        tool_args = tool_call["args"]
        tool_id = tool_call.get("id", "unknown")
        
        logger.info(f"🔧 执行工具: {tool_name} 参数: {tool_args}")
        
        # 查找对应的工具函数
        tool_function = None
        for tool in hr_tools:
            if tool.name == tool_name:
                tool_function = tool
                break
        
        if tool_function:
            result = tool_function.invoke(tool_args)
            
            # 创建工具消息
            from langchain_core.messages import ToolMessage
            tool_message = ToolMessage(
                content=str(result),
                tool_call_id=tool_id,
                name=tool_name
            )
            tool_results.append(tool_message)
            
            logger.info(f"✅ 工具 {tool_name} 执行成功")
        else:
            from langchain_core.messages import ToolMessage
            error_message = ToolMessage(
                content=f"工具 {tool_name} 不存在",
                tool_call_id=tool_id,
                name=tool_name
            )
            tool_results.append(error_message)
    
    # 根据当前任务决定返回哪个智能体
    agent = current_task.get("agent", "orchestrator")
    if agent == "orchestrator":
        next_agent = "orchestrator"
    elif agent == "candidate_analysis":
        next_agent = "candidate_analysis"
    elif agent == "candidate_deep_analysis":
        next_agent = "candidate_deep_analysis"
    elif agent == "record_keeping":
        next_agent = "record_keeping"  
    elif agent == "workbench_ui":
        next_agent = "workbench_ui"
    else:
        next_agent = "completion"
    
    return {
        "messages": tool_results,
        "next_agent": next_agent,
        "task_results": {f"{agent}_tool_execution": "completed"}
    }

def completion_handler(state: MultiAgentState) -> Dict[str, Any]:
    """完成处理器 - 生成最终响应"""
    logger.info("🏁 Completion Handler: 生成最终响应")
    
    # 提取最终的AI消息作为响应
    final_message = ""
    for msg in reversed(state["messages"]):
        if isinstance(msg, AIMessage) and msg.content:
            # 跳过包含工具调用的消息
            if not (hasattr(msg, 'tool_calls') and msg.tool_calls):
                final_message = msg.content
                break
    
    if not final_message:
        final_message = "任务已完成，感谢使用HR智能助手！"
    
    return {
        "final_response": final_message,
        "status": "completed",
        "next_agent": END
    }

# ==================== 5. 路由函数 ====================

def route_next_agent(state: MultiAgentState) -> str:
    """智能体路由函数"""
    next_agent = state.get("next_agent", "completion")
    logger.info(f"🗺️ 路由到下一个智能体: {next_agent}")
    
    if next_agent == "orchestrator":
        return "orchestrator"
    elif next_agent == "candidate_analysis":
        return "candidate_analysis"
    elif next_agent == "candidate_deep_analysis":
        return "candidate_deep_analysis"
    elif next_agent == "record_keeping":
        return "record_keeping"
    elif next_agent == "workbench_ui":
        return "workbench_ui"
    elif next_agent == "tool_executor":
        return "tool_executor"
    elif next_agent == "completion":
        return "completion"
    else:
        return "completion"

# ==================== 6. 多智能体系统构建 ====================

class MultiAgentHRSystem:
    """多智能体HR系统"""
    
    def __init__(self):
        self.graph = None
        self.initialized = False
    
    def initialize(self) -> bool:
        """初始化多智能体系统"""
        logger.info("🚀 初始化多智能体HR系统...")
        
        # 初始化数据管理器
        data_manager.initialize()
        logger.info(f"📊 数据加载完成: {len(data_manager.resumes)}个简历, {len(data_manager.jobs)}个岗位")
        
        # 构建LangGraph - 添加递归限制和检查点
        workflow = StateGraph(MultiAgentState)
        
        # 添加智能体节点
        workflow.add_node("interaction", interaction_module)
        workflow.add_node("orchestrator", orchestrator_agent)
        workflow.add_node("candidate_analysis", candidate_analysis_agent)
        workflow.add_node("candidate_deep_analysis", candidate_deep_analysis_agent)
        workflow.add_node("record_keeping", record_keeping_agent)
        workflow.add_node("workbench_ui", workbench_ui_agent)
        workflow.add_node("tool_executor", tool_executor)
        workflow.add_node("completion", completion_handler)
        
        # 设置入口点
        workflow.set_entry_point("interaction")
        
        # 添加智能路由
        workflow.add_conditional_edges(
            "interaction",
            route_next_agent,
            {
                "orchestrator": "orchestrator",
                "completion": "completion"
            }
        )
        
        workflow.add_conditional_edges(
            "orchestrator", 
            route_next_agent,
            {
                "candidate_analysis": "candidate_analysis",
                "candidate_deep_analysis": "candidate_deep_analysis",
                "record_keeping": "record_keeping",
                "workbench_ui": "workbench_ui", 
                "tool_executor": "tool_executor",
                "completion": "completion"
            }
        )
        
        workflow.add_conditional_edges(
            "candidate_analysis",
            route_next_agent,
            {
                "candidate_deep_analysis": "candidate_deep_analysis",
                "workbench_ui": "workbench_ui",
                "record_keeping": "record_keeping",
                "tool_executor": "tool_executor",
                "completion": "completion"
            }
        )
        
        workflow.add_conditional_edges(
            "candidate_deep_analysis",
            route_next_agent,
            {
                "workbench_ui": "workbench_ui",
                "record_keeping": "record_keeping",
                "tool_executor": "tool_executor",
                "completion": "completion"
            }
        )
        
        workflow.add_conditional_edges(
            "record_keeping",
            route_next_agent,
            {
                "workbench_ui": "workbench_ui",
                "tool_executor": "tool_executor", 
                "completion": "completion"
            }
        )
        
        workflow.add_conditional_edges(
            "workbench_ui",
            route_next_agent,
            {
                "tool_executor": "tool_executor",
                "completion": "completion"
            }
        )
        
        workflow.add_conditional_edges(
            "tool_executor",
            route_next_agent,
            {
                "orchestrator": "orchestrator",
                "candidate_analysis": "candidate_analysis",
                "candidate_deep_analysis": "candidate_deep_analysis",
                "record_keeping": "record_keeping",
                "workbench_ui": "workbench_ui",
                "completion": "completion"
            }
        )
        
        # 编译图
        self.graph = workflow.compile()
        self.initialized = True
        
        logger.info("✅ 多智能体HR系统初始化完成！")
        logger.info("🎯 系统架构: Interaction → Orchestrator → Specialists → Tools → Completion")
        return True
    
    async def process_request(self, user_query: str, user_id: str = "hr_user_001") -> Dict[str, Any]:
        """处理用户请求"""
        if not self.initialized:
            return {"success": False, "error": "系统未初始化"}
        
        logger.info(f"🎯 开始处理用户请求: {user_query}")
        
        # 初始状态
        initial_state = {
            "original_query": user_query,
            "user_id": user_id,
            "timestamp": datetime.now().isoformat(),
            "status": "started",
            "messages": []
        }
        
        # 执行多智能体工作流 - 设置递归限制
        config = {"recursion_limit": 10}
        final_state = await self.graph.ainvoke(initial_state, config=config)
        
        # 构建响应
        response = {
            "success": True,
            "message": final_state.get("final_response", "任务完成"),
            "session_id": final_state.get("session_id"),
            "status": final_state.get("status", "completed"),
            "ui_commands": final_state.get("ui_commands", []),
            "analysis_results": final_state.get("analysis_results", {}),
            "task_results": final_state.get("task_results", {}),
            "agent_workflow": "Multi-Agent System: Interaction → Orchestrator → Specialists → Tools → Completion"
        }
        
        logger.info("✅ 多智能体请求处理完成")
        return response

# 全局系统实例
multi_agent_hr_system = MultiAgentHRSystem()

if __name__ == "__main__":
    import asyncio
    
    async def main():
        # 初始化系统
        multi_agent_hr_system.initialize()
        
        # 测试请求
        test_query = "筛选出有3年以上Python经验的候选人，按匹配度排序"
        result = await multi_agent_hr_system.process_request(test_query)
        
        print("🎯 测试结果:")
        print(json.dumps(result, indent=2, ensure_ascii=False))
    
    asyncio.run(main())
